package cn.edu.zzuli.nothinglink.exception;

import cn.edu.zzuli.nothinglink.entity.R;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

//jsr 303全局异常捕捉，方便返回给前端校验信息
@RestControllerAdvice
public class ValidException {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R exceptionHandler(HttpServletRequest req, MethodArgumentNotValidException e) {
//        String errmsg = e.getBindingResult().getFieldError().getField()
//                + "字段: " + e.getBindingResult().getFieldError().getDefaultMessage();
//        return errmsg;
        String errmsg = Objects.requireNonNull(
                e.getBindingResult().getFieldError())
                .getDefaultMessage();
        return R.error().add("error", errmsg);
    }

    @ExceptionHandler(value = TokenExpiredException.class)
    public R tokenExpiredException(HttpServletRequest req) {
        return R.error().add("error", "身份过期，请重新登录！:)");
    }

    @ExceptionHandler(value = JWTDecodeException.class)
    public R JWTDecodeException(HttpServletRequest req, HttpServletResponse response) {
        response.setStatus(400);
        return R.error().add("error", "token 校验失败:)");
    }
}
